#include             "global.h"
#include             "syscalls.h"
#include             "protos.h"


#include			"Definitions.h"

void ready_sort(void) {
	PCB* current = NULL;
	PCB* next = NULL;
	bool end = false;
	while (!end) {
		 current = pidList;
		 next = (PCB*) current->next;
		end = true;
		current = pidList;
		next = (PCB*) current->next;
		while (next != NULL) {
			if (current->pri < next->pri) {
				end = false;
				swap(1,current, next);
				current = next;
				next = (PCB*) next->next;
			} else {
				current = next;
				next = (PCB*) next->next;
			}
		}
	}
}

void timer_sort(void) {
	PCB* current = NULL;
	PCB* next = NULL;
	bool end = false;
	while (!end) {
		end = true;
		current = pidList;
		next = (PCB*) current->next;
		while (next != NULL) {
			if (current->pri < next->pri) {
				end = false;
				swap(0,current, next);
				current = next;
				next = (PCB*) next->next;
			} else {
				current = next;
				next = (PCB*) next->next;
			}
		}
	}
}

void swap(bool x, PCB *Prev, PCB *Curr) {
	PCB *temp = (PCB*) Prev->prev;
	if (temp == NULL) {
		Curr->prev = NULL;
		if (x) {
			pidList = Curr;
		} else {
			timerList = Curr;
		}
	} else {
		temp->next = Curr;
		Curr->prev = temp;
	}
	temp = (PCB*) Curr->next;
	if (temp == NULL) {
		Prev->next = NULL;
	} else {
		Prev->next = temp;
		temp->prev = Prev;
	}
	Curr->next = Prev;
	Prev->next = Curr;
}

